package com.xyhuo.leetcode.january;

import java.util.*;

/**
 * 分数到小数
 * https://leetcode.cn/problems/fraction-to-recurring-decimal/
 *
 * @time 2024/1/29
 */
public class FractionToDecimal {

//    public static void main(String[] args) {
//        FractionToDecimal ftd = new FractionToDecimal();
//        ftd.fractionToDecimal(1, 2);
//    }

    public String fractionToDecimal(int numerator, int denominator) {
        String pre = "0";
        if (numerator == 0) {
            return pre;
        }
        long nume = numerator, deno = denominator;
        int fCount = 0;
        if (nume < 0) {
            fCount++;
            nume = Math.abs(nume);
        }
        if (deno < 0) {
            fCount++;
            deno = Math.abs(deno);
        }
        if (nume >= deno) {
            pre = String.valueOf(nume / deno);
            nume = nume - (nume / deno) * deno;
        }

        StringBuilder finalSb = new StringBuilder();
        if (fCount % 2 != 0) {
            finalSb.append("-");
        }
        finalSb.append(pre);
        Map<Long, Integer> existSet = new HashMap<>();

        int len = -1;
        if (nume > 0) {
            finalSb.append(".");
            existSet.put(nume, finalSb.length());
            while (true) {
                if (finalSb.length() > 10000 || nume == 0) {
                    break;
                }
                int count = 0;
                while (nume < deno) {
                    count++;
                    nume *= 10;
                }
                for (int i = 0; i < count - 1; i++) {
                    finalSb.append("0");
                }
                finalSb.append(nume / deno);
                nume = nume - (nume / deno) * deno;
                if (existSet.containsKey(nume)) {
                    len = finalSb.length() - existSet.get(nume);
                    break;
                }
                existSet.put(nume, finalSb.length());
            }
            if (len != -1) {
                finalSb.insert(finalSb.length() - len, "(");
                finalSb.append(")");
            }
        }

        return finalSb.toString();
    }

}
